package com.example.mainstream.ui.user;

import android.Manifest;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;

import com.example.shopapp.App;
import com.example.shopapp.R;
import com.example.shopapp.adapter.OnUploadListener;
import com.example.shopapp.adapter.UploadImgAdapter;
import com.example.shopapp.bean.CircleEntity;
import com.example.shopapp.bean.Luntan;
import com.example.shopapp.dao.CircleEntityDao;
import com.example.shopapp.dao.LuntanDao;
import com.example.shopapp.database.GreenDaoManager;
import com.example.shopapp.databinding.ActivityAddCircleBinding;
import com.example.shopapp.utils.ImageEngine;
import com.example.shopapp.utils.Utils;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.huantansheng.easyphotos.utils.permission.PermissionUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.project.base.baseui.BaseNormalActivity;
import cn.project.base.utils.Constant;
import cn.project.base.utils.Event;

/**
 * @authors: 唐辉
 * @description:
 **/
public class AddCircleActivity extends BaseNormalActivity<ActivityAddCircleBinding> implements OnUploadListener {

    UploadImgAdapter uploadImgAdapter;
    List<String> stringList1 = new ArrayList<>();
    String circle_id;
    Luntan luntan = new Luntan();

    LuntanDao luntanDao;
    CircleEntityDao circleEntityDao ;




    @Override
    protected int getLayoutId() {
        return  R.layout.activity_add_circle;
    }

    @Override
    protected void initView() {
        uploadImgAdapter = new UploadImgAdapter(AddCircleActivity.this,stringList1,this);
    }

    @Override
    protected void initData() {
        luntanDao = GreenDaoManager.getmInstance().getDaoSession().getLuntanDao();
        circleEntityDao = GreenDaoManager.getmInstance().getDaoSession().getCircleEntityDao();
        initListener();
    }


    protected void initListener() {
        mBinding.gvUpload.setAdapter(uploadImgAdapter);
        mBinding.toolbar.rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mBinding.toolbar.tvTitle.setText("添加动态");

        if (PermissionUtil.checkAndRequestPermissionsInActivity(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
            preLoadAlbums();
        }

        mBinding.btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content= mBinding.etContent.getText().toString();
                if (TextUtils.isEmpty(content)){
                    showToast("请输入内容");
                    return;
                }
                circle_id = System.currentTimeMillis()+"";
                luntan.setUser_id(App.getInstance().user.getUser_id());
                luntan.setContent(content);
                luntan.setPic(circle_id);
                luntan.setTime(Utils.getTime());
                goToSend(luntan,circle_id);

            }
        });
    }




    /**
     * 预加载相册扫描，可以增加点速度，写不写都行
     * 该方法如果没有授权读取权限的话，是无效的，所以外部加不加权限控制都可以，加的话保证执行，不加也不影响程序正常使用。
     */
    private void preLoadAlbums() {
        EasyPhotos.preLoad(this);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull final String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        PermissionUtil.onPermissionResult(this, permissions, grantResults,
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        preLoadAlbums();
                    }

                    @Override
                    public void onShouldShow() {
                    }

                    @Override
                    public void onFailed() {
                    }
                });
    }

    @Override
    public void onUploadClick() {
        EasyPhotos
                .createAlbum(AddCircleActivity.this, true,true, ImageEngine.getInstance())
                .setCount(9)
                .setFileProviderAuthority("com.example.shopapp.fileprovider")
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        //获取file，进行对应操作
                        if (photos.size()>0){
                            stringList1.clear();
                            for (int i = 0; i < photos.size(); i++) {
                                stringList1.add(photos.get(i).path);
                            }
                            uploadImgAdapter.addNewData(stringList1);
                            mBinding.gvUpload.setAdapter(uploadImgAdapter);

                        }
                    }
                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Override
    public void onUploadItemClick(String path) {

    }

    private void goToSend(Luntan luntan,String circle_id){
        luntan.setAuthority("0");
        luntan.setId(System.currentTimeMillis());
        luntanDao.insert(luntan);
        long sysid = System.currentTimeMillis();
        if (stringList1.size() >0){
            for (int i = 0; i < stringList1.size(); i++) {
                CircleEntity circleEntity  = new CircleEntity();
                circleEntity.setCircle_id(circle_id);
                circleEntity.setId(sysid+i);
                circleEntity.setUser_id(App.getInstance().user.getUser_id());
                circleEntity.setPath(stringList1.get(i));
                circleEntityDao.insert(circleEntity);
            }
        }
        showToast("发布成功");
        EventBus.getDefault().postSticky(new Event(Constant.CIRCLR_ADD_REFRESH));
        finish();
    }

}
